package com.mpsc.api.config.util;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;

public class SpringContextUtil {
    private static ApplicationContext applicationContext;

    //获取上下文
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //设置上下文
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    //通过名字获取上下文中的bean
    public static Object getBean(String name) {
        try {
            return applicationContext.getBean(name);
        } catch (NoSuchBeanDefinitionException ex) {
            return null;
        }
    }

    //通过类型获取上下文中的bean
    public static Object getBean(Class<?> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static void main(String[] args) {
        //获取context
//        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContextUtil.getApplicationContext();
//        //获取BeanFactory
//        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
//        //创建bean信息.
//        String beanName ="123";
//        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(HikariDataSource.class);
//
//        beanDefinitionBuilder.addPropertyValue("id", "1");
//        beanDefinitionBuilder.addPropertyValue("name", "张三");
//        //判断Bean是否已经注册
//        Object beanObject = SpringContextUtil.getBean(beanName);
//        if (beanObject != null) {
//            System.out.println(String.format("Bean %s 已注册", beanName));
//        } else {
//        }
//            //动态注册bean.
//            defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
//            //获取动态注册的bean.
//            beanObject = SpringContextUtil.getBean(beanName);
//
    }
}
